
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: CollectionFieldModel.java 295 2010-01-13 21:03:17Z archie.cobbs $
 */

package org.dellroad.sidekar.schema.model;

import java.lang.reflect.Method;

import org.dellroad.sidekar.schema.SchemaMismatchException;

/**
 * Abstract superclass for collection schema types.
 */
public abstract class CollectionFieldModel extends ComplexFieldModel {

    private SimpleFieldModel elementModel;

    private Method accessMethod;

    // Normal constructor
    CollectionFieldModel(String typeName) {
        super(typeName);
    }

    // Copy constructor
    CollectionFieldModel(CollectionFieldModel original, SchemaModel schemaModel) {
        super(original);
        if (original.elementModel != null)
            this.elementModel = FieldDeepCopier.copy(original.elementModel, schemaModel);
        this.accessMethod = original.accessMethod;
    }

    /**
     * Get the type of the collection elements.
     */
    public SimpleFieldModel getElementModel() {
        return this.elementModel;
    }
    public void setElementModel(SimpleFieldModel elementModel) {
        this.elementModel = elementModel;
    }

    /**
     * Get the Java method used to access this field on the associated entity's class.
     * This property is optional.
     */
    public Method getAccessMethod() {
        return this.accessMethod;
    }
    public void setAccessMethod(Method accessMethod) {
        this.accessMethod = accessMethod;
    }

    @Override
    public void validate(SchemaModel schema) {
        super.validate(schema);
        this.elementModel.validate(schema, true);
    }

    @Override
    public void checkSameField(FieldModel model) {
        super.checkSameField(model);
        CollectionFieldModel that = (CollectionFieldModel)model;
        try {
            this.elementModel.checkSameField(that.elementModel);
        } catch (SchemaMismatchException e) {
            throw new SchemaMismatchException("element types differ: " + e.getMessage(), e);
        }
    }
}

